import VXETable from 'vxe-table'
import createBem from '@Components/assets/js/utils/bem'
import { tableNamespace } from '../../../config'
import { handlePropsMethod } from '../../../utils'
import './index.scss'

const Bem = createBem(`${tableNamespace}__select`)

function getList({ list, $tableInstance }) {
  if (list instanceof Array) return list
  return $tableInstance?.selectOptionsList?.[list]?.list || []
}

VXETable.renderer.add('Select', {
  autofocus: '.el-input__inner',
  renderEdit(h, renderOpts, params) {
    const { options = {}, events = {} } = renderOpts
    const { row, column, $table } = params
    const { multiple, labelKey, valueKey } = options
    const { onChange } = events
    const _options = handlePropsMethod(options, params, ['disabled', 'loading'])
    const value = row[column.property]
    if (multiple && value && !(value instanceof Array)) {
      row[column.property] = [value]
    }

    function handleChange() {
      $table.updateStatus(params)
      onChange?.({ cellValue: row[column.property], row, column })
      if (labelKey) {
        row[labelKey] = getList(renderOpts).find(
          i => i.value === row[column.property]
        )?.label
      }
    }
    return [
      <el-select
        class={Bem()}
        placeholder="请选择"
        size={this.$store.getters.size}
        v-model={row[column.property]}
        collapse-tags
        filterable
        props={_options}
        onChange={handleChange}
      >
        {getList(renderOpts).map(i => (
          <el-option
            key={valueKey ? i.value[valueKey] : i.value}
            label={i.label}
            value={i.value}
          />
        ))}
      </el-select>
    ]
  },
  renderCell(h, renderOpts, params) {
    const { row, column } = params
    const { formatter } = renderOpts
    const rawValue = row[column.property]
    const cellValue =
      getList(renderOpts).find(i => i.value === rawValue)?.label || rawValue

    const content = formatter
      ? formatter({ cellValue, row, column })
      : cellValue

    return [<span>{content}</span>]
  }
})

/** @type { Column } */
export const options = {
  showOverflow: 'tooltip',
  align: 'left'
}
